package org.jetlinks.demo.protocol.siterwell.tcp.message;

import lombok.Getter;
import org.jetlinks.demo.protocol.siterwell.tcp.TcpPayload;
import org.jetlinks.demo.protocol.siterwell.tcp.util.ByteUtils;
import org.jetlinks.demo.protocol.siterwell.tcp.util.Validator;

/**
 * 赛特威尔网关 tcp 报文协议格式
 * 网关设备发送到平台的消息类
 * 命令类型数据的格式
 * <p>
 * 第1字节   57		固定头（心跳数据除外）
 * 第2字节   01		流水号（回复时，此流水号需要一致）
 * 第3字节   20		版本号
 * 第4-6字节 339053		网关ID
 * 第7字节   16		网关GSM信号
 * 第8字节   16		子设备RF信号
 * 第9字节   01		子设备类型
 * 第10字节  3F		子设备最高2位ID
 * 第11字节  0A		网关类型(固定为0A)
 * 第12字节  21		命令 ， 写取传感器
 * 第13字节  00		数据长度
 * 中间字节是数据
 * 最后1个字节 27		校验值
 */
@Getter
public abstract class AbstractCommandRequest implements TcpPayload {

    private byte[] sourceBytes;
    private String hexPayload;
    private String hexFixedHeader;
    private String hexSerialNumber;
    private String hexVersion;
    private String gateWayId;
    private String hexGSMSignal;
    private String hexRFSignal;
    private String hexChildDeviceType;
    private String hexChildHigh2ID;
    private String hexGatewayType;   // 固定为 0a
    private String hexCommand;
    private String hexDataLength;
    private String hexDataSource;
    private String hexCheckValue;


    @Override
    public void fromBytes(byte[] bytes, int offset) {
        this.sourceBytes = bytes;
        this.hexPayload = ByteUtils.byte2HexStr(bytes);
        Validator.validateData(bytes);
        this.parseHexPayload();
        this.parseData();

    }

    @Override
    public byte[] toBytes() {
        return sourceBytes;
    }

    /**
     * 解析数据部分
     */
    protected abstract void parseData();


    private void parseHexPayload() {
        int totalLen = hexPayload.length();
        int byteTotal = totalLen / 2;
        this.hexFixedHeader = ByteUtils.subHexStrByByte(hexPayload, 0, 1);
        this.hexSerialNumber = ByteUtils.subHexStrByByte(hexPayload, 1, 2);
        this.hexVersion = ByteUtils.subHexStrByByte(hexPayload, 2, 3);
        this.gateWayId = ByteUtils.subHexStrByByte(hexPayload, 3, 6);
        this.hexGSMSignal = ByteUtils.subHexStrByByte(hexPayload, 6, 7);
        this.hexRFSignal = ByteUtils.subHexStrByByte(hexPayload, 7, 8);
        this.hexChildDeviceType = ByteUtils.subHexStrByByte(hexPayload, 8, 9);
        this.hexChildHigh2ID = ByteUtils.subHexStrByByte(hexPayload, 9, 10);
        this.hexGatewayType = ByteUtils.subHexStrByByte(hexPayload, 10, 11);
        this.hexCommand = ByteUtils.subHexStrByByte(hexPayload, 11, 12);
        this.hexDataLength = ByteUtils.subHexStrByByte(hexPayload, 12, 13);
        int dataLength = ByteUtils.hexToInt(this.hexDataLength);
        this.hexDataSource = ByteUtils.subHexStrByByte(hexPayload, 13, 13 + dataLength);
        this.hexCheckValue = ByteUtils.subHexStrByByte(hexPayload, byteTotal - 1, byteTotal);

    }


}
